package com.qf.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.Objects;

/**
 * @author jiangjingbo
 * @version V1.0
 * @Project java2203
 * @Package com.qf.utils
 * @Description:
 * @Date 2022/5/31 16:26
 */
public class MybatisUtils {
    private volatile  static SqlSession SQL_SESSION;

    public static <T> T getMapper(Class<T> cls) throws Exception{
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SQL_SESSION = sqlSessionFactory.openSession(true);
        return SQL_SESSION.getMapper(cls);
    }
    public static void close(){
        if(Objects.nonNull(SQL_SESSION)){
            SQL_SESSION.close();
        }
    }
}
